package de.gameduell.framework.game.card.sort {
	import de.gameduell.framework.game.card.Card;	
	import de.gameduell.framework.game.card.CardStack;
	import de.gameduell.framework.game.card.sort.ISortMode;

	/**
	 * Sorting mode specific to the game Hearts
	 * @author dkum
	 */
	public class FamilySortMode implements ISortMode {

		private var _reverse:Boolean;
		private var _sortDirection:int;
		private var _familySortMap:Array = [3,2,1,0];
		private var _symbolSortMap:Array = [7, 8, 9, 10, 11, 12, 13];

		/**
		 * Class contructor
		 * @param reverse	if reverse is true stack will be sorted ascending
		 */
		public function FamilySortMode(aFamily:int, aSortDirection:int = 1, aReverse:Boolean = false){
			_reverse = aReverse;
			_sortDirection = aSortDirection;
			
			for(var i:* in _familySortMap){
				if(_familySortMap[i] == aFamily){
					_familySortMap.splice(i,1);
				}
			}
			_familySortMap.unshift(aFamily);
		}
		
		/**
		 * Overrides the sort map with a new sort order.
		 * @param sortMap	new order to sort a card stack.
		 */
		public function set familySortMap(sortMap:Array):void {
			_familySortMap = sortMap;
		}
		
		/**
		 * Overrides the sort map with a new symbol sort order.
		 * @param sortMap	new order to sort a card stack.
		 */
		public function set symbolSortMap(sortMap:Array):void {
			_symbolSortMap = sortMap;
		}
		
		/**
		 * sorts stack.
		 * @param stack		stack to sort
		 */
		public function sortCards(stack:CardStack):void {
			stack.cards.sort(order);
			if(_reverse){
				stack.cards.reverse();
			}
		}

		/**
		 * provides order rules for two cards to compare
		 * 
		 * @param card1 & card2		compares this two cards
		 * @return order of this two cards
		 */
		private function order(card1:Card, card2:Card):int {
			switch(true) {
				case(card1.family == card2.family):
					for(var i:* in _symbolSortMap) {	
						if(_symbolSortMap[i] == card1.symbol ) {
							return 1 * _sortDirection;
						}	
						if(_symbolSortMap[i] == card2.symbol) {
							return -1 * _sortDirection;
						}
					}	
				case(card1.family != card2.family):
					for(var j in _familySortMap) {	
						if(_familySortMap[j] == card1.family ) {
							return -1;
						}	
						if(_familySortMap[j] == card2.family) {
							return 1;
						}
					}	
			}
			return -1; // should not be reached
		}

		/**
		 * change direction of sorting
		 * @param isReverse		if true - stack will be sorted ascending
		 */
		public function sortReverse(isReverse:Boolean):void {
			_reverse = isReverse;
		}
	}
}
